/**
 * Axios 封装
 */
import axios from 'axios';
import { ErrorMessage } from '@/types/common/components.ts';
import { auth } from '@/store/common/auth.ts';
import { user } from '@/store/common/user.ts';
import { message } from '@/components/lib/message';

const token = auth();
const userManager = user();
const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_URL,
  timeout: 6000,
});

const errorMessage: ErrorMessage = {
  code: 500,
  msg: '系统异常',
};

// request拦截器
service.interceptors.request.use(
  (config) => {
    config.headers['Content-Type'] = 'application/json';
    if (token.$state.token) {
      config.headers['APEXEDU'] = token.$state.token;
    }
    return config;
  },
  () => {
    // Do something with request error
    return Promise.reject(errorMessage);
  },
);

// response 拦截器
service.interceptors.response.use(
  (response) => {
    const code = response.status;
    if (code < 200 || code > 300) {
      return Promise.reject(errorMessage);
    } else {
      return response.data;
    }
  },
  (error) => {
    try {
      errorMessage.code = error.response.data.status;
      errorMessage.msg = error.response.data.message;
      if (errorMessage.msg.indexOf('Exception') !== -1) {
        errorMessage.msg = '系统异常！';
        errorMessage.code = 500;
      }
      if (errorMessage.code === 403) {
        // 令牌过期的情况，执行登录
        token.updateToken('');
        // 清空用户信息
        userManager.updateUser({ username: '', nickName: '', avatarPath: '' });
      }
      return Promise.reject(errorMessage);
    } catch (e) {
      if (error.response.status === 500) {
        message({ msg: '登录已过期，请重新登录！', theme: 'error', close: true });
        token.updateToken('');
        userManager.updateUser({
          username: '',
          nickName: '',
          avatarPath: '',
        });
        window.location.replace('/login');
      } else {
        const url = error.response.request.responseURL.replace(import.meta.env.VITE_BASE_URL, '');
        message({ msg: '无效的地址(' + url + ')', theme: 'error', close: true });
        if (error.toString().indexOf('Error: timeout') !== -1) {
          errorMessage.msg = '请求超时，请稍后再试！';
          errorMessage.code = 500;
          return Promise.reject(errorMessage);
        }
      }
    }
  },
);

export default service;
